<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input v-model="queryInfo.query" clearable @clear='getUserList' placeholder="请输入内容"
            class="input-with-select">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="17">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table border stripe :data="userList">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名" width="100px"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色" width="100px"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template v-slot='scoped'>
            <el-switch v-model="scoped.row.mg_state" @change="changeState(scoped.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <!-- 修改按钮 -->
          <template v-slot='{row}'>
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(row)"></el-button>
            <el-button v-if="row.id!==500" @click="remove(row.id)" type="danger" size="mini" icon="el-icon-delete">
            </el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable='false'>
              <el-button @click="distribution(row)" type="warning" size="mini" icon="el-icon-setting">
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[1,2,5]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
    <el-dialog @close='resetAddFrom' title="添加" :visible.sync="addDialogVisible" width="50%">
      <el-form ref='addFormRef' label-width="80px" :model="addFrom" :rules=" addFormRules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model=" addFrom.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model=" addFrom.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model=" addFrom.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model=" addFrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAddFrom">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog @close='resetEditForm' title="编辑" :visible.sync="editDialogVisible" width="50%">
      <el-form ref='editFormRef' label-width="80px" :model="editFrom" :rules=" addFormRules">
        <el-form-item label="用户名" prop="username">
          <el-input disabled v-model=" editFrom.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model=" editFrom.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model=" editFrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditFrom">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="分配角色" :visible.sync="roleDialogVisible" @close="selectedRoleId=null">
      <p>用户名:{{userInfo.username}}</p>
      <p>当前角色{{userInfo.role_name}}</p>
      <el-select v-model="selectedRoleId" placeholder="请选择">
        <el-option v-for="item in roleList" :key="item.value" :label="item.roleName" :value="item.id">
        </el-option>
      </el-select>
      <template #footer>
        <el-button @click="roleDialogVisible=false">取消</el-button>
        <el-button @click="saveRole" type="primary">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // callback() 校验通过
    // callback(new Error())校验失败
    const validateEmail = function (rule, value, callback) {
      const reg = /^([a-zA-Z0-9._-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (reg.test(value)) {
        callback()
      } else {
        callback(new Error('邮箱不符合格式'))
      }
    }

    const validateMobile = function (rule, value, callback) {
      const reg = /^1[3456789]\d{9}$/
      if (reg.test(value)) {
        callback()
      } else {
        callback(new Error('手机号不符合格式'))
      }
    }

    return {
      selectedRoleId: null,
      roleList: [],
      userInfo: {},
      roleDialogVisible: false, // 分配角色对话框
      // 修改用户信息对话框信息
      editFrom: {
        username: '',
        email: '',
        mobile: ''
      },
      editDialogVisible: false, // 默认编辑对话框的状态为隐藏
      // 添加新用户的信息对话框信息
      addFrom: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addDialogVisible: false, // 默认添加新用户对话框的状态为隐藏
      // 添加对话框的正则规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在3到10之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在6到15之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },

          { validator: validateMobile, trigger: 'blur' }

        ]
      },
      queryInfo: {
        query: '',
        pagenum: 1, // 当前页
        pagesize: 5// 默认每页展示数据
      },
      total: 0,
      userList: [] // 用户裂变信息

    }
  },
  methods: {
    async saveRole () {
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoleId })
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.$message.success('更新成功')
      this.roleDialogVisible = false
      this.getUserList()
    },
    // 分配角色
    async distribution (row) {
      this.userInfo = row
      this.roleDialogVisible = true
      const { data: res } = await this.$http.get('roles')
      this.roleList = res.data
      // console.log(res)
    },
    // 点击删除按钮删除该用户
    remove (id) {
      // console.log(id)
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`users/${id}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功!')
        this.getUserList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 修改用户信息
    saveEditFrom () {
      this.$refs.editFormRef.validate(async bool => {
        if (!bool) return console.log('校验失败')
        const { data: res } = await this.$http.put(`users/${this.editFrom.id}`, {
          email: this.editFrom.email,
          mobile: this.editFrom.mobile
        })
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.$message.success('修改成功')
        this.editDialogVisible = false
        this.getUserList()
      })
    },
    // 关闭对话框清空所有
    resetEditForm () {
      this.$refs.editFormRef.resetFields()
    },
    // 点击修改按钮编辑对话框展示
    showEditDialog (row) {
      // console.log(row)
      this.editDialogVisible = true
      this.editFrom = row
    },
    // 添加新用户
    saveAddFrom () {
      this.$refs.addFormRef.validate(async bool => {
        if (!bool) return console.log('校验失败')
        const { data: res } = await this.$http.post('users', this.addFrom)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    // 关闭对话框清空所有
    resetAddFrom () {
      this.$refs.addFormRef.resetFields()
    },
    // 更新用户状态
    async changeState (row) {
      // console.log(row)
      const { data: res } = await this.$http.put(`users/${row.id}/state/${row.mg_state}`)
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.$message.success('更新成功')
    },
    // 改变页数
    handleCurrentChange (current) {
      this.queryInfo.pagenum = current
      this.getUserList()
    },
    // 改变每页展示几条数据
    handleSizeChange (size) {
      this.queryInfo.pagesize = size
      this.getUserList()
    },
    // 获取用户列表数据
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      this.total = res.data.total
      this.userList = res.data.users
      // console.log(res)
    }
  },
  computed: {},
  watch: {},
  filters: {},
  components: {},
  created () {
    this.getUserList()
  },
  mounted () { }
}
</script>

<style scoped lang='less'>
</style>
